package com.topcheer.common.base.loadBalance;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author xutao
 * @Package com.topcheer.common.base.loadBalance
 * @Description: 平滑加权轮训算法
 * 每个地址有权重、当前权重
 * 1 初始化当前权重为0
 * 2 当前权重=当前权重+权重
 * 3 找到当前权重值最大的  并将当前权重减去总权重值
 * 4 返回该ip
 *
 * @date 2020/4/10 16:48
 */
public class WeightRoundRibbon {

    private static Map<String,Integer> map = new LinkedHashMap<>();
    private static Map<String,Weight> weightMap = new LinkedHashMap<>();
    static {
        map.put("192.168.0.1",5);
        map.put("192.168.0.2",1);
        map.put("192.168.0.3",1);
    }

    public static String getServer(){

        if(CollectionUtils.isEmpty(weightMap)){
            for(String ip: map.keySet()){
                weightMap.put(ip,new Weight(ip,map.get(ip),0));
            }
        }
        Integer totalWeight = weightMap.values().stream()
                .mapToInt(Weight::getWeight)
                .sum();
        for(Weight weight:weightMap.values()){
            weight.setCurrentWeight(weight.getCurrentWeight()+weight.getWeight());
        }
        Optional<Weight> first = weightMap.values().stream().sorted(Comparator.comparingInt(Weight::getCurrentWeight).reversed()).findFirst();
        if(first.isPresent()){
            Weight weight = first.get();
            weight.setCurrentWeight(weight.getCurrentWeight()-totalWeight);
            return weight.getIp();
        }
        return null;

    }
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(getServer());
        }

    }
}

@Getter
@Setter
@AllArgsConstructor
class Weight{
    private String ip;
    private Integer weight;
    private Integer currentWeight;
}
